import os

from installation_make_package_conf import get_package_name, BACKEND_MAIN, DATA_FILES, FRONT_ADMIN, \
    FRONT_CUSTOMER, FRONT_PORTAL, artifacts_conf_map
from instools import check_dir_exists, logger, check_file_exists, make_dir_p, \
    cmd_with_result, copy_file_to_dir, cmd, get_current_script_folder


class TaskType:
    def __init__(self):
        pass

    FILE_COPY_TO_FOLDER = 1  # copy one file to dst folder path
    UNZIP = 2  # unzip one zip file to dst folder path
    FOLDER_COPY = 3  # copy all files under folder to dst folder path
    FILE_COPY_TO_FILE = 4


class FileTask:
    # all folder path should end with /
    def __init__(self, name, src_path, dst_folder_path, task_type,
                 service_need_restart="",
                 is_clean_dst=False):
        self.name = name
        self.src_path = src_path
        self.dst_path = dst_folder_path
        self.is_clean_dst = is_clean_dst
        self.task_type = task_type
        self.service_name = service_need_restart

    def __pre_check(self):
        if self.task_type == TaskType.FILE_COPY_TO_FOLDER:
            check_file_exists(self.src_path)
            check_dir_exists(self.dst_path)
        elif self.task_type == TaskType.FILE_COPY_TO_FILE:
            check_file_exists(self.src_path)
            check_dir_exists(os.path.dirname(self.dst_path))
        elif self.task_type == TaskType.FOLDER_COPY:
            check_dir_exists(self.src_path)
            check_dir_exists(self.dst_path)
        elif self.task_type == TaskType.UNZIP:
            check_file_exists(self.src_path)
            check_dir_exists(self.dst_path)
        return True

    def do_task(self):
        if not self.__pre_check():
            logger.info("-------------------- Skip %s FileTask  %s" % (self.name, vars(self)))
            return
        logger.info("----------------> Start %s FileTask %s" % (self.name, vars(self)))
        if self.is_clean_dst:
            cmd_with_result("rm -rf %s*" % self.dst_path)
        if self.task_type == TaskType.FILE_COPY_TO_FOLDER:
            copy_file_to_dir(self.src_path, self.dst_path)
        elif self.task_type == TaskType.FILE_COPY_TO_FILE:
            cmd_with_result("cp -f %s %s" % (self.src_path, self.dst_path))
        elif self.task_type == TaskType.UNZIP:
            cmd("unzip -o %s -d %s" % (self.src_path, self.dst_path))
        elif self.task_type == TaskType.FOLDER_COPY:
            cmd_with_result("cp -rf %s* %s" % (self.src_path, self.dst_path))
        if len(self.service_name.strip()) > 0:
            cmd_with_result("sudo  systemctl restart %s" % self.service_name)
            cmd_with_result("systemctl status %s" % self.service_name)
        cmd_with_result("ls -la %s" % self.dst_path)
        logger.info("<------------------- End %s FileTask  %s" % (self.name, vars(self)))


def pre_check(args):
    check_dir_exists(os.path.dirname(args.nginx_conf_path))
    check_dir_exists(os.path.dirname(args.systemd_conf_path))
    make_dir_p(args.frontend_path)
    make_dir_p(args.backend_path)
    check_file_exists(args.java_path)


def get_package_full_path(key):
    if key is None or len(key) == 0:
        return None
    return get_current_script_folder() + '/' + get_package_name(key)


def do_deployment():
    deployment_conf_list = {
        BACKEND_MAIN: [
            FileTask(
                src_path=get_package_full_path(BACKEND_MAIN),
                dst_folder_path="/home/CI/project_admin/service/starter-admin.jar",
                task_type=TaskType.FILE_COPY_TO_FILE, name="Deploy Back End Service",
                service_need_restart="sysctl_admin",
                is_clean_dst=False), ],
        DATA_FILES: [  # data file
            FileTask(
                src_path=get_package_full_path(DATA_FILES),
                dst_folder_path="/home/CI/project_admin/package/data-temp/",
                task_type=TaskType.UNZIP, name="Deploy Data",
                service_need_restart="",
                is_clean_dst=True),

            FileTask(src_path="/home/CI/project_admin/package/data-temp/00_webdata/",
                     dst_folder_path="/home/techinfo/webdata/",
                     task_type=TaskType.FOLDER_COPY, name="Deploy Data",
                     service_need_restart="",
                     is_clean_dst=False),

            FileTask(src_path="/home/CI/project_admin/package/data-temp/00_webdata/admin_migrate_file_data/",
                     dst_folder_path="/home/techinfo/webdata/",
                     task_type=TaskType.FOLDER_COPY, name="Deploy old Data",
                     service_need_restart="",
                     is_clean_dst=False)],
        FRONT_ADMIN: [
            FileTask(
                src_path=get_package_full_path(FRONT_ADMIN),
                dst_folder_path="/home/CI/project_admin/front_admin/",
                task_type=TaskType.UNZIP, name="Deploy Front Admin",
                service_need_restart="nginx",
                is_clean_dst=True)],
        FRONT_CUSTOMER: [
            FileTask(
                src_path=get_package_full_path(FRONT_CUSTOMER),
                dst_folder_path="/home/CI/project_admin_customer/front/Customer/",
                task_type=TaskType.UNZIP, name="Deploy Front Customer",
                service_need_restart="nginx",
                is_clean_dst=True)
        ],
        FRONT_PORTAL: [
            FileTask(
                src_path=get_package_full_path(FRONT_PORTAL),
                dst_folder_path="/home/CI/project_admin_portal/front/",
                task_type=TaskType.UNZIP, name="Deploy Front Portal",
                service_need_restart="nginx",
                is_clean_dst=True)
        ],
    }

    for key in artifacts_conf_map.keys():
        file_task_list = deployment_conf_list[key]
        logger.debug("buildType: {}   fileTask: {}".format(key, file_task_list))
        for task in file_task_list:
            task.do_task()


def main():
    logger.info(__file__)
    logger.info(os.environ)
    do_deployment()
    return


if __name__ == "__main__":
    main()
